#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'James Iter'
__date__ = '15/12/20'
__contact__ = 'james.iter.cn@gmail.com'
__copyright__ = '(c) 2015 by James Iter.'


from flask import Blueprint, request, make_response
import json
import jimit as ji

from models.initialize import app, ts
from models import Utils, Rules, RecodeOperate


blueprint = Blueprint(
    'oo',
    __name__,
    url_prefix='/oo'
)


@app.before_request
@Utils.dumps2response
def r_before_request():
    global ts
    try:
        ts = ji.Common.ts()
    except ji.JITError, e:
        return json.loads(e.message)


@Utils.dumps2response
def r_record_create(name):
    try:
        args_rules = [
            Rules.JSON.value,
        ]

        ji.Check.previewing(args_rules, {'json': request.json})

        oo = RecodeOperate()
        oo.name = name
        oo.kv = request.json
        oo.create()

    except ji.PreviewingError, e:
        return json.loads(e.message)


@Utils.dumps2response
def r_record_get(name):
    ret = dict()
    ret['state'] = ji.Common.exchange_state(20000)
    ret['list'] = list()
    try:
        oo = RecodeOperate()
        oo.name = name
        oo.filter_str = request.args.get('filter_str')
        ret['list'] = oo.get()
    except ji.PreviewingError, e:
        return json.loads(e.message)

    return ret


@Utils.dumps2response
def r_record_update(name, _id):
    try:
        args_rules = [
            Rules.JSON.value,
        ]

        ji.Check.previewing(args_rules, {'json': request.json})

        oo = RecodeOperate()
        oo.name = name
        oo.kv = request.json
        oo.kv['id'] = _id
        oo.update()

    except ji.PreviewingError, e:
        return json.loads(e.message)


@Utils.dumps2response
def r_record_delete(name, _id):
    try:
        oo = RecodeOperate()
        oo.name = name
        oo.kv = {'id': _id}
        oo.delete()

    except ji.PreviewingError, e:
        return json.loads(e.message)
